package com.demo.ognl.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import ognl.Ognl;
import ognl.OgnlException;

import java.util.Map;

/**
 * @author peter
 * @date 2021/11/21 下午11:42
 */
@Slf4j
public class OgnlWrapper {

    private Map<?, ?> jsonMap;

    private static ObjectMapper objectMapper = new ObjectMapper();

    public OgnlWrapper(Map<?,?> m) {
        this.jsonMap = m;
    }

    public OgnlWrapper(Object o){
        this.jsonMap = objectMapper.convertValue(o, Map.class);
    }

    public <T> T get(String expression) {
        try {
            return (T) Ognl.getValue(expression, this.jsonMap);
        } catch (OgnlException e) {
            log.warn(String.format("get value with expression:[%s] due to error, return null instead of",
                    expression), e);
            return null;
        }
    }

    public Long getLong(String expression) {
        try {
            Object obj = Ognl.getValue(expression, this.jsonMap);
            if (null == obj)
                return null;
            try {
                return Long.parseLong(obj.toString());
            } catch (NumberFormatException nfe) {
                log.warn(String.format("get value with expression:[%s] due to error, return null. value[%s] cannot be cast to java.lang.Long",
                        expression,
                        obj.toString()));
                return null;
            }
        } catch (OgnlException e) {
            log.trace(String.format("get value with expression:[%s] due to error, return null instead of",
                    expression), e);
            return null;
        }
    }

    public Integer getInt(String expression) {
        try {
            Object obj = Ognl.getValue(expression, this.jsonMap);
            if (null == obj)
                return null;
            try {
                return Integer.parseInt(obj.toString());
            } catch (NumberFormatException nfe) {
                log.warn(String.format("get value with expression:[%s] due to error, return null. value[%s] cannot be cast to java.lang.Integer",
                        expression,
                        obj.toString()));
                return null;
            }
        } catch (OgnlException e) {
            log.trace(String.format("get value with expression:[%s] due to error, return null instead of",
                    expression), e);
            return null;
        }
    }

    @Override
    public String toString() {
        return String.format("OgnlWrapper[%s]", this.jsonMap.toString());
    }
}
